var gulp = require('gulp');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var clean = require('gulp-clean');

var buildConfig = require('./config/build.config.js');
var pkg = require('./package.json');

var argv = require('minimist')(process.argv.slice(2));

var gutil = require('gulp-util');
var rename = require('gulp-rename');

var stripDebug = require('gulp-strip-debug');
var header = require('gulp-header');
var footer = require('gulp-footer');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');

var server = require('gulp-server-livereload');

var IS_RELEASE_BUILD = !!argv.release;
if (IS_RELEASE_BUILD) {
  gutil.log(
    gutil.colors.red('--release:'),
    'Building release version (minified, debugs stripped)...'
  );
}

// Scripts
gulp.task('scripts', function() {

  var bundleFiles = buildConfig.coreFiles;
  return gulp.src(bundleFiles)
    .pipe(gulpif(IS_RELEASE_BUILD, stripDebug()))
    .pipe(concat('mobird.js'))
    .pipe(header(buildConfig.closureStart))
    .pipe(footer(buildConfig.closureEnd))
    .pipe(gulp.dest(buildConfig.dist))
    .pipe(gulpif(IS_RELEASE_BUILD, uglify()))
    .pipe(gulpif(IS_RELEASE_BUILD, rename({
      extname: '.min.js'
    })))
    .pipe(gulpif(IS_RELEASE_BUILD, gulp.dest(buildConfig.dist)));
});

gulp.task('jshint', function() {
  return gulp.src(['scripts/**/*.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(require('jshint-summary')({
      fileColCol: ',bold',
      positionCol: ',bold',
      codeCol: 'green,bold',
      reasonCol: 'cyan'
    })))
    .pipe(jshint.reporter('fail'));
});

// Clean
gulp.task('clean', function() {
  return gulp.src([buildConfig.dist], {
    read: false
  }).pipe(clean());
});

gulp.task('server', function() {
  gulp.src('.')
    .pipe(server({
      livereload: false,
      directoryListing: false,
      open: true,
      defaultFile: 'examples/index.html',
      log: 'debug'
    }));
});